package com.chuji.crmcj.act;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.SalesNoticeInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;
import com.jauker.widget.BadgeView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NoticeActivity extends BaseActivity {
    /*通知布局*/
    private ListView lv_notice_table;
    /*自定义适配器*/
    private CustomNoticeAdapter customNoticeAdapter;
    /*通知公告数据存储*/
    List<SalesNoticeInfo.ApiParamObjEntity> salesNoticeData;
    /*通知公告数据*/
    private SalesNoticeInfo salesNoticeInfo;
    /*回退*/
    private ImageView iv_back;
    /*头像*/
    String Num;
    //销售员ID
    String SalesID;
    private BadgeView badgeView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice);
        lv_notice_table = (ListView) findViewById(R.id.lv_notice_table);
        iv_back = (ImageView) findViewById(R.id.iv_notice_Back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //请求网络数据
        initDa();
        //给ListView设置点击事件
//        lv_notice_table.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view,
//                                    int position, long id) {
////                UIUtils.showToastSafe("点击了第"+position+"个Item");
//                Jump.toNextActivity(NoticeActivity.this, NoticeDetailActivity.class);
//            }
//        });
//        //下拉刷新
//        lv_notice_table.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            public void onRefresh(
//                    PullToRefreshBase<ListView> refreshView) {
//                initData();
//            }
//        });
    }


    @Override
    protected void onStart() {
        super.onStart();


        //获取通知信息
        getSalesNoticeData();
    }

    private void initDa() {
    }

    private void getSalesNoticeData() {
//        if (salesNoticeData == null) {
            salesNoticeData = new ArrayList<SalesNoticeInfo.ApiParamObjEntity>();
//        }
        requestData();
    }

    private void requestData() {
        //初始化Volley
        SalesID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        String strURL = String.format(UrlUtils.GET_SALES_NOTICE + "&SalesID=" + SalesID + "&PageSize=" + "20" + "&PageIndex=" + "1");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                salesNoticeInfo = JSON.parseObject(response, SalesNoticeInfo.class);
                salesNoticeData.addAll(salesNoticeInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customNoticeAdapter == null) {
                            //创建适配器
                            customNoticeAdapter = new CustomNoticeAdapter();
                            //填充数据
                            lv_notice_table.setAdapter(customNoticeAdapter);
                        } else {
                            customNoticeAdapter.notifyDataSetChanged();
                        }
                        /*得到消息ID*/
                        lv_notice_table.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                Intent intent = new Intent(UIUtils.getContext(), NoticeDetailActivity.class);
                                intent.putExtra("name", salesNoticeData.get(position).getUserName());
                                intent.putExtra("title", salesNoticeData.get(position).getTitle());
                                intent.putExtra("time", salesNoticeData.get(position).getSendTime());
                                intent.putExtra("avatar", salesNoticeData.get(position).getAvatar());
                                intent.putExtra("content", salesNoticeData.get(position).getContent());
                                intent.putExtra("post", salesNoticeData.get(position).getPositionName());
                                if(salesNoticeData.get(position).getIsRead().equals("0")) {
                                    uploadIsRead(salesNoticeData.get(position).getID());
                                }
                                System.out.println(salesNoticeData.get(position).getContent() + "------------------------------------");
                                startActivity(intent);
                            }
                        });
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }

    public void uploadIsRead(String ID) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ID", ID);
        postRequest(UrlUtils.SUBMIT_SALES_ISREAD, map, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                UIUtils.showToastSafe("消息已读");
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initListener() {

    }

    //初始化组件
    private void init() {

    }
    /**
     * 获取Icon对应的bitmap
     *
     * @param res
     * @param resId
     * @return
     */
    private Bitmap getResIcon(Resources res, int resId) {
        Drawable icon = res.getDrawable(resId);
        if (icon instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) icon;
            return bd.getBitmap();
        } else {
            return null;
        }
    }

    /**
     * 在给定的图片的右上角加上红色提醒数量
     *
     * @param icon 给定的图片
     * @return 带联系人数量的图片
     */
    private Bitmap generatorContactCountIcon(Bitmap icon, int count) {
        // 初始化画布
        int iconSize = (int) getResources().getDimension(
                android.R.dimen.app_icon_size);
        Bitmap contactIcon = Bitmap.createBitmap(iconSize, iconSize,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(contactIcon);

        // 拷贝图片
        Paint iconPaint = new Paint();
        iconPaint.setDither(true);//防抖动
        iconPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理，这样，当你选择Drawable时，会有抗锯齿的效果
        Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
        Rect dst = new Rect(0, 0, iconSize, iconSize);
        canvas.drawBitmap(icon, src, dst, iconPaint);

        // 启用抗锯齿和使用设备的文本字距
        Paint countPaint = new Paint(Paint.ANTI_ALIAS_FLAG
                | Paint.DEV_KERN_TEXT_FLAG);
        countPaint.setColor(Color.RED);
        countPaint.setTextSize(20f);
        countPaint.setTypeface(Typeface.DEFAULT_BOLD);
        canvas.drawText(String.valueOf(count), iconSize - 18, 25, countPaint);
        return contactIcon;
    }

    class CustomNoticeAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return salesNoticeData.size();
        }

        @Override
        public Object getItem(int position) {
            return salesNoticeData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_notice, null);
                //初始化组件
                viewHolder.mIv_client_image = (com.chuji.crmcj.view.CircleImageView) convertView.findViewById(R.id.iv_client_image);
                viewHolder.mTv_notice_title = (TextView) convertView.findViewById(R.id.tv_notice_title);
                viewHolder.mTv_name = (TextView) convertView.findViewById(R.id.tv_name);
                viewHolder.mTv_post = (TextView) convertView.findViewById(R.id.tv_post);
                viewHolder.mTv_notice_time = (TextView) convertView.findViewById(R.id.tv_notice_time);
                viewHolder.ll_image_view = (FrameLayout) convertView.findViewById(R.id.ll_image_view);
                viewHolder.iv_tag = (ImageView) convertView.findViewById(R.id.iv_tag);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (salesNoticeData.size() != 0) {
                viewHolder.mTv_name.setText(salesNoticeData.get(position).getUserName());
                viewHolder.mTv_notice_title.setText(salesNoticeData.get(position).getTitle());
                viewHolder.mTv_notice_time.setText(salesNoticeData.get(position).getSendTime());
                if (salesNoticeData.get(position).getAvatar() != null) {
                    Glide.with(UIUtils.getContext())
                            .load(UrlUtils.ImageIP + salesNoticeData.get(position).getAvatar())
                            .into(viewHolder.mIv_client_image);
                } else {
                    viewHolder.mIv_client_image.setImageResource(R.drawable.morentouxiang);
                }
                if (salesNoticeData.get(position).getIsRead().equals("0")) {
//                    badgeView = new BadgeView(UIUtils.getContext());
//                    badgeView.setTargetView(viewHolder.ll_image_view);
//                    badgeView.setBadgeGravity(Gravity.RIGHT | Gravity.TOP);
////                  badgeView.setBackgroundResource(R.drawable.yuandian);
////                  badgeView.setBackground(10, Color.parseColor("#ff0000"));
//                    badgeView.setBackgroundResource(R.drawable.yuandian);
//                    badgeView.setText("");
                    viewHolder.iv_tag.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.iv_tag.setVisibility(View.GONE);
                }
            } else {
                UIUtils.showToastSafe("暂无数据");
            }
            return convertView;
        }
    }

    static class ViewHolder {
        private com.chuji.crmcj.view.CircleImageView mIv_client_image;
        private TextView mTv_notice_title;
        private TextView mTv_name;
        private TextView mTv_post;
        private TextView mTv_notice_time;
        private FrameLayout ll_image_view;
        private ImageView iv_tag;
    }
}
